<!-- Created by henian.xu on 2018/7/27. -->

<template>
    <el-select
        v-bind="$attrs"
        v-model="model"
        filterable
        clearable
        @blur="onBlur"
    >
        <el-option
            v-for="(item) in listData"
            :key="item.id"
            :label="item.name"
            :value="item.id + ''"
        />
    </el-select>
</template>

<script>
import emitter from 'element-ui/src/mixins/emitter';
import { Rs } from '@/api';

export default {
    name: 'DictionariesPicker',
    mixins: [emitter],
    data() {
        return {
            listData: [],
        };
    },
    props: {
        value: {
            type: [String, Number],
            required: true,
        },
        // 这个值是字典值的 Code
        type: {
            type: String,
            required: true,
        },
    },
    computed: {
        model: {
            get() {
                return this.value + '';
            },
            set(val) {
                this.$emit('input', val);
                this.dispatch('ElFormItem', 'el.form.change', [val]);
            },
        },
        listMap() {
            const res = {};
            this.listData.forEach(item => {
                res[item.id] = item;
            });
            return res;
        },
    },
    methods: {
        getListData() {
            return Rs.Dic.entry({ dicCode: this.type }).then(json => {
                const res = json.data.data;
                this.listData = res;
            });
        },
        getNameById(id) {
            const item = this.listMap[id];
            if (!item) return '';
            return item.name;
        },
        onBlur(event) {
            this.$emit('blur', event);
            this.dispatch('ElFormItem', 'el.form.blur', [this.currentValue]);
        },
    },
    created() {
        this.getListData();
    },
};
</script>

<style lang="scss">
</style>
